<template>
  <div class="suixiao-chart">
    <el-row :gutter="20" align="middle">
      <el-col :span="12">
        <div class="chart-title">各区县随销收入</div>
      </el-col>
      <el-col :span="6">
        <el-select
          v-model="chartType"
          placeholder="请选择图表类型"
          @change="handleChartTypeChange"
          style="width: 110%"
        >
          <el-option label="平均随销收入" value="average"></el-option>
          <el-option label="总随销收入" value="total"></el-option>
        </el-select>
      </el-col>
      <el-col :span="5">
        <el-date-picker
          v-model="salarySelectedDate"
          style="width: 100%"
          type="month"
          value-format="YYYY-MM"
          format="YYYY-MM"
          placeholder="选择月份"
          :picker-options="pickerOptions"
          @change="handleSalaryDateChange"
          :disabled-date="disabledDate"
        />
      </el-col>
      <!-- 添加这行以对齐 -->
      <div class="chart-description" style="visibility: hidden">
        注：差值为最大值减最小值
      </div>
    </el-row>
    <div ref="suixiaoChart" class="chart" style="height: 400px" />
  </div>
</template>

<script>
import { ElDatePicker, ElRow, ElCol, ElSelect, ElOption } from "element-plus";
import {
  totalMomSalary,
  averageIncentive,
  totalIncentive,
} from "@/api/dwxc/salary";
import { totalHbresIncome, MomSalary } from "@/api/dwxc/income";
import * as echarts from "echarts";

export default {
  components: {
    ElDatePicker,
    ElRow,
    ElCol,
    ElSelect,
    ElOption,
  },
  props: {
    selectedDate: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      chartType: "average",
      totalSalaryData: null,
      salarySelectedDate: this.selectedDate,
      pickerOptions: {
        disabledDate: (time) => {
          const now = new Date();
          const firstDayOfMonth = new Date(
            now.getFullYear(),
            now.getMonth(),
            1
          );
          return time.getTime() >= firstDayOfMonth.getTime();
        },
      },
      salaryData: null,
      hbData: null,
      district: "全市", // 添加默认区县为"全市"
    };
  },
  mounted() {
    this.initializeChart();
  },
  watch: {
    selectedDate: {
      handler(newVal) {
        // 只有当外部传入的日期与当前日期不同时才更新
        if (newVal !== this.salarySelectedDate) {
          this.salarySelectedDate = newVal;
          // 根据当前图表类型加载相应数据
          this.loadData(newVal);
          // this.getSalaryData(newVal);
        }
      },
      immediate: false,
    },
  },
  methods: {
    disabledDate(time) {
      // Disable current month and future months
      const currentDate = new Date();
      const currentYear = currentDate.getFullYear();
      const currentMonth = currentDate.getMonth(); // 0-11

      const selectedDate = new Date(time);
      const selectedYear = selectedDate.getFullYear();
      const selectedMonth = selectedDate.getMonth(); // 0-11 // Disable if selected date is current or future month

      return (
        selectedYear > currentYear ||
        (selectedYear === currentYear && selectedMonth >= currentMonth)
      );
    },

    initializeChart() {
      // 如果有传入的日期，使用传入的日期
      if (this.salarySelectedDate) {
        this.loadData(this.salarySelectedDate);
      } else {
        // 如果没有传入日期，使用上个月作为默认日期
        const now = new Date();
        const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        const defaultDate =
          lastMonth.getFullYear() +
          "-" +
          String(lastMonth.getMonth() + 1).padStart(2, "0") +
          "-01";
        this.salarySelectedDate = defaultDate;
        this.loadData(defaultDate);
      }
    },

    // 总薪酬图表相关
    async handleChartTypeChange() {
      // 根据图表类型加载数据并渲染图表
      if (this.chartType === "average") {
        // 如果平均薪酬数据不存在，则获取数据
        if (!this.salaryData) {
          await this.getSalaryData(this.salarySelectedDate);
        } else {
          this.initSalaryChart(
            this.$refs.suixiaoChart,
            this.salaryData,
            this.hbData
          );
        }
      } else {
        // 如果总薪酬数据不存在，则获取数据
        if (!this.totalSalaryData) {
          await this.getTotalSalaryData(this.salarySelectedDate);
        } else {
          this.initTotalSalaryChart(
            this.$refs.suixiaoChart,
            this.totalSalaryData,
            this.hbData
          );
        }
      }
    },

    handleSalaryDateChange(date) {
      console.log("suixiaoChart handleSalaryDateChange called with:", date);
      // 先更新本地日期，避免watch重复触发
      this.salarySelectedDate = date;
      this.loadData(date);
      // 向父组件发送事件
      this.$emit("handle-date-change", date);
    },
    async loadData(time) {
      if (this.chartType === "average") {
        await this.getSalaryData(time);
      } else {
        await this.getTotalSalaryData(time);
      }
    },
    // 获取总薪酬数据
    async getTotalSalaryData(time) {
      const queryTime = time || this.salarySelectedDate;

      if (!queryTime) {
        this.$message.warning("请先选择查询时间！");
        return;
      }

      try {
        let formattedTime = queryTime;
        if (queryTime.match(/^\d{4}-\d{2}$/)) {
          formattedTime = queryTime + "-01";
        } else if (queryTime.match(/^\d{4}-\d{2}-\d{2}$/)) {
          formattedTime = queryTime;
        }
        // 添加 district 参数
        const params = {
          time: formattedTime,
          district: this.district, // 传递 district 参数
        };
        // 调用新接口获取总薪酬数据
        const res = await totalIncentive(params);

        // 修改部分：添加错误处理，防止totalMomSalary接口不存在时导致整个功能失败
        let hbres = null;
        try {
          hbres = await totalHbresIncome(params);
        } catch (error) {
          console.warn("获取总薪酬环比数据失败:", error);
          // 如果接口不存在或出错，继续使用默认数据
        }

        const data = res.data || res;
        const totalMomData = hbres ? hbres.data || hbres : null;

        if (data) {
          const processedData = this.processTotalSalaryData(data);
          const processedHbData = totalMomData
            ? this.processHbData(totalMomData)
            : {
                categories: processedData.categories,
                values: processedData.categories.map(() => 0),
              };

          this.totalSalaryData = processedData;
          this.hbData = processedHbData;
          this.initTotalSalaryChart(
            this.$refs.suixiaoChart,
            processedData,
            processedHbData
          );
        } else {
          this.$message.warning("后端返回数据为空，使用默认数据显示");
          this.initTotalSalaryChart(this.$refs.suixiaoChart, null);
        }
      } catch (error) {
        console.error("获取总薪酬统计数据失败：", error);
        this.$message.error("获取总薪酬统计数据失败：" + error.message);
        this.initTotalSalaryChart(this.$refs.suixiaoChart, null);
      }
    },
    // 处理总薪酬数据
    processTotalSalaryData(data) {
      const categories = ["全市"];
      const totalValues = [];
      const diffValues = [];
      const momValues = []; // 添加环比率数据
      console.log("data为：", data);

      // 处理全市总数据
      if (data.totalIncentive !== undefined && data.totalIncentive !== null) {
        totalValues.push(data.totalIncentive);
      } else {
        totalValues.push(0);
      }

      // 处理各区县数据
      if (
        data.totalIncentiveDetails &&
        Array.isArray(data.totalIncentiveDetails)
      ) {
        data.totalIncentiveDetails.forEach((item) => {
          categories.push(item.name || "");
          totalValues.push(item.totalIncentive || item.total || 0);
          // 如果有环比和差值数据，也需要处理
          diffValues.push(item.difference || 0);
          momValues.push(item.mom || 0);
        });
      }

      return {
        categories: categories,
        totalValues: totalValues,
        diffValues: diffValues,
        momValues: momValues, // 添加环比率数据
      };
    },

    async getSalaryData(time) {
      const queryTime = time || this.salarySelectedDate;

      if (!queryTime) {
        this.$message.warning("请先选择查询时间！");
        return;
      }

      try {
        let formattedTime = queryTime;
        if (queryTime.match(/^\d{4}-\d{2}$/)) {
          formattedTime = queryTime + "-01";
        } else if (queryTime.match(/^\d{4}-\d{2}-\d{2}$/)) {
          formattedTime = queryTime;
        }
        // 添加 district 参数
        const params = {
          time: formattedTime,
          district: this.district, // 传递 district 参数
        };

        const res = await averageIncentive(params);
        const hbres = await MomSalary(params);

        // 处理不同的响应数据结构
        const salaryData = res.data || res; // aveSalary可能直接返回数据

        console.log(salaryData);
        const momData = hbres.data || hbres; // MomSalary包装在{code, msg, data}中

        if (salaryData) {
          const processedData = this.processSalaryData(salaryData);
          // 即使 momData 为空也要处理
          const processedHbData = momData
            ? this.processHbData(momData)
            : {
                categories: processedData.categories,
                values: processedData.categories.map(() => 0),
              };

          this.salaryData = processedData;
          this.hbData = processedHbData;
          this.initSalaryChart(
            this.$refs.suixiaoChart,
            processedData,
            processedHbData
          );
        } else {
          this.$message.warning("后端返回数据为空，使用默认数据显示");
          this.initSalaryChart(this.$refs.suixiaoChart, null, null);
        }
      } catch (error) {
        console.error("获取薪酬统计数据失败：", error);
        this.$message.error("获取薪酬统计数据失败：" + error.message);
        this.initSalaryChart(this.$refs.suixiaoChart, null, null);
      }
    },
    processSalaryData(data) {
      const categories = ["全市"];
      const values = [];
      console.log("data为：", data);

      // 处理全市平均数据
      if (data.avgIncentive !== undefined && data.avgIncentive !== null) {
        values.push(data.avgIncentive);
      } else {
        values.push(0);
      }

      // 处理各区县数据
      if (data.avgIncentiveDetails && Array.isArray(data.avgIncentiveDetails)) {
        data.avgIncentiveDetails.forEach((item) => {
          categories.push(item.name || "");
          values.push(item.avgIncentive || 0);
        });
      }

      return {
        categories: categories,
        values: values,
      };
    },
    processHbData(data) {
      const categories = ["全市"];
      const values = [];

      if (data.cityMom !== undefined && data.cityMom !== null) {
        values.push(data.cityMom);
      } else {
        values.push(0);
      }

      if (data.salaries && typeof data.salaries === "object") {
        Object.keys(data.salaries).forEach((district) => {
          categories.push(district);
          values.push(data.salaries[district] || 0);
        });
      }

      return {
        categories: categories,
        values: values,
      };
    },
    initSalaryChart(chartRef, salaryProcessedData, hbProcessedData) {
      if (!chartRef) return;

      if (chartRef._echarts_instance_) {
        chartRef._echarts_instance_.dispose();
      }

      const chart = echarts.init(chartRef);

      if (
        salaryProcessedData &&
        salaryProcessedData.categories &&
        salaryProcessedData.values
      ) {
        // 确保 hbProcessedData 存在且数据长度匹配
        const validHbData =
          hbProcessedData &&
          hbProcessedData.values &&
          hbProcessedData.values.length ===
            salaryProcessedData.categories.length
            ? hbProcessedData.values
            : salaryProcessedData.categories.map(() => 0);
        chart.setOption({
          title: {
            // text: '各区县月均薪酬统计',
            // left: 'center'
          },
          grid: {
            top: "8%",
            left: "2%",
            right: "2%", // 增加右边距防止x轴标签溢出
            bottom: "0%", // 增加底部边距防止x轴标签被截断
            containLabel: true,
            borderWidth: 0, // 去掉网格边框
            show: false, // 隐藏网格背景
          },
          xAxis: {
            type: "category",
            data: salaryProcessedData.categories,
            axisLabel: {
              rotate: 45,
              fontSize: 12,
              fontWeight: "normal",
              color: "#6A6A6A",
              fontFamily: "Arial, sans-serif",
              formatter: function (value) {
                return value;
              },
            },
          },
          yAxis: [
            {
              type: "value",
              name: "随销收入(元)",
              min: 0,
            },
            {
              type: "value",
              name: "环比(%)",
              scale: true,
              splitLine: {
                show: true,
                lineStyle: {
                  color: ["#E6E6E6"],
                  type: "dashed",
                },
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: "#999",
                },
              },
              axisLabel: {
                formatter: "{value}%",
                color: "#666",
              },
              // 自动计算合适的范围，确保0%在中间
              min: function (value) {
                // 获取数据的最小值和最大值
                const dataMin = value.min;
                const dataMax = value.max;

                // 如果数据都是正数，从0开始
                if (dataMin >= 0) {
                  return 0;
                }
                // 如果数据都是负数，让最大值为0
                if (dataMax <= 0) {
                  return dataMin;
                }
                // 如果有正有负，让0在中间
                const absMax = Math.max(Math.abs(dataMin), Math.abs(dataMax));
                return -absMax;
              },
              max: function (value) {
                const dataMin = value.min;
                const dataMax = value.max;

                // 如果数据都是正数，使用数据最大值
                if (dataMin >= 0) {
                  return dataMax;
                }
                // 如果数据都是负数，最大值为0
                if (dataMax <= 0) {
                  return 0;
                }
                // 如果有正有负，让0在中间
                const absMax = Math.max(Math.abs(dataMin), Math.abs(dataMax));
                return absMax;
              },
            },
          ],
          series: [
            {
              name: "平均随销收入",
              data: salaryProcessedData.values,
              type: "bar",
              itemStyle: {
                color: function (params) {
                  return params.dataIndex === 0 ? "#91CC75" : "#91CC75";
                },
              },
              label: {
                show: true,
                position: "top",
                fontSize: 12,
                color: "#333",
                fontWeight: "normal",
                formatter: function (params) {
                  if (
                    params.value === 0 ||
                    params.value === null ||
                    params.value === undefined
                  ) {
                    return "";
                  }
                  return Math.round(params.value);
                },
              },
            },
            {
              name: "收入环比率",
              data: validHbData,
              type: "line",
              yAxisIndex: 1,
              smooth: true, // 平滑曲线
              symbol: "circle", // 数据点形状
              symbolSize: 6, // 数据点大小
              lineStyle: {
                width: 2,
                color: "#FAC858",
              },
              itemStyle: {
                color: function (params) {
                  // 根据数值正负设置不同颜色
                  return params.value >= 0 ? "#FF4500" : "#3BA272";
                },
                borderColor: "#fff",
                borderWidth: 2,
              },
              label: {
                show: false,
                position: function (params) {
                  // 负数标签显示在下方，正数显示在上方
                  return params.value >= 0 ? "top" : "bottom";
                },
                fontSize: 11,
                color: function (params) {
                  return params.value >= 0 ? "#FF4500" : "#FAC858";
                },
                fontWeight: "bold",
                formatter: function (params) {
                  if (params.value === null || params.value === undefined) {
                    return "";
                  }
                  if (params.value === 0) {
                    return "0%";
                  }
                  return (
                    (params.value > 0 ? "+" : "") +
                    params.value.toFixed(1) +
                    "%"
                  );
                },
              },
              markLine: {
                silent: true,
                symbol: "none",
                label: {
                  show: false,
                },
                data: [
                  {
                    yAxis: 0,
                    lineStyle: {
                      color: "rgba(51, 51, 51, 0.5)", // 使用rgba设置透明度，0.8表示80%不透明度
                      type: "solid",
                      //   width: 1, // 增加线条宽度，从1改为2
                    },
                  },
                ],
              },
            },
          ],
          tooltip: {
            trigger: "axis",
            formatter: function (params) {
              let result = `${params[0].name}<br/>`;
              params.forEach(function (item) {
                if (item.seriesIndex === 0) {
                  result += `${item.marker} ${item.seriesName}: ${item.value}元<br/>`;
                } else if (item.seriesIndex === 1) {
                  if (item.value !== null && item.value !== undefined) {
                    result += `${item.marker} ${item.seriesName}: ${item.value}%`;
                  }
                }
              });
              return result;
            },
          },
        });

        setTimeout(() => {
          chart.resize();
        }, 100);
      } else {
        chart.setOption({
          title: {
            // text: "各区县月均薪酬统计",
            // left: "center",
          },
          grid: {
            top: "8%",
            left: "2%",
            right: "2%",
            bottom: "0%",
            containLabel: true,
            borderWidth: 0,
            show: false,
          },
          xAxis: {
            type: "category",
            data: [
              "全市",
              "柴桑区",
              "浔阳区",
              "濂溪区",
              "共青城",
              "庐山市",
              "彭泽县",
              "德安县",
              "武宁县",
              "永修县",
              "湖口县",
              "瑞昌县",
              "都昌县",
            ],

            axisLabel: {
              rotate: 45,
              fontSize: 12,
              fontWeight: "normal",
              color: "#666666",
              fontFamily: "Arial, sans-serif",
              formatter: function (value) {
                return value;
              },
            },
          },
          yAxis: [
            {
              type: "value",
              name: "随销收入(元)",
            },
            {
              type: "value",
              name: "环比(%)",
            },
          ],
          series: [
            {
              name: "平均随销收入",
              data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              type: "bar",

              itemStyle: {
                color: function (params) {
                  return params.dataIndex === 0 ? "#ff7f50" : "#91CC75";
                },
              },
              label: {
                show: true,
                position: "top",
                fontSize: 12,
                color: "#333",
                fontWeight: "normal",
                formatter: function (params) {
                  if (
                    params.value === 0 ||
                    params.value === null ||
                    params.value === undefined
                  ) {
                    return "";
                  }
                  return Math.round(params.value) + "元";
                },
              },
            },
            {
              name: "收入环比率",
              data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              type: "line",
              yAxisIndex: 1,
              smooth: true,
              symbol: "circle",
              symbolSize: 6,
              lineStyle: {
                width: 2,
                color: "#FAC858",
              },
              itemStyle: {
                color: "#FF4500",
                borderColor: "#fff",
                borderWidth: 2,
              },
            },
          ],
          tooltip: {
            trigger: "axis",
          },
        });

        setTimeout(() => {
          chart.resize();
        }, 100);
      }

      chartRef._echarts_instance_ = chart;
    },
    initTotalSalaryChart(chartRef, processedData, hbProcessedData) {
      if (!chartRef) return;

      if (chartRef._echarts_instance_) {
        chartRef._echarts_instance_.dispose();
      }

      const chart = echarts.init(chartRef);

      if (
        processedData &&
        processedData.categories &&
        processedData.totalValues
      ) {
        // 使用传入的环比数据或默认数据
        const validHbData =
          hbProcessedData &&
          hbProcessedData.values &&
          hbProcessedData.values.length === processedData.categories.length
            ? hbProcessedData.values
            : processedData.categories.map(() => 0);

        chart.setOption({
          title: {
            // text: '各区县总薪酬统计',
            // left: 'center'
          },
          grid: {
            top: "8%",
            left: "2%",
            right: "0%",
            bottom: "0%",
            containLabel: true,
            borderWidth: 0,
            show: false,
          },
          xAxis: {
            type: "category",
            data: processedData.categories,
            axisLabel: {
              rotate: 45,
              fontSize: 12,
              fontWeight: "normal",
              color: "#6A6A6A",
              fontFamily: "Arial, sans-serif",
            },
            axisLine: {
              show: false, // 隐藏横坐标轴线
            },
            axisTick: {
              show: false, // 隐藏横坐标轴刻度线
            },
          },
          yAxis: [
            {
              type: "log",
              name: "随销收入(万元)",
              logBase: 10,
              axisLabel: {
                formatter: function (value) {
                  // if (value >= 100000000) {
                  //   return (value / 100000000).toFixed(0) + "亿";
                  // } else if (value >= 10000) {
                  //   return (value / 10000).toFixed(0) + "万";
                  // } else {
                  //   return value;
                  // }
                  if (value < 10000){
                    return (value / 10000).toFixed(1);
                  }
                  else{
                    return (value / 10000).toFixed(0);
                  }
                },
                color: "#666",
              },
              // 添加以下配置以改善对数轴的刻度显示
              scale: true,
              splitNumber: 5, // 设置分割段数
            },
            {
              type: "value",
              name: "环比(%)",
              min: -150,
              max: 150,
              axisLabel: {
                formatter: "{value}%",
                color: "#666",
              },
            },
          ],
          series: [
            {
              name: "总收入",
              data: processedData.totalValues,
              type: "bar",
              yAxisIndex: 0, // 使用第一个Y轴（对数轴）
              itemStyle: {
                color: "#91CC75",
              },
              label: {
                show: true,
                position: "top",
                fontSize: 12,
                color: "#333",
                fontWeight: "normal",
                formatter: function (params) {
                  if (
                    params.value === 0 ||
                    params.value === null ||
                    params.value === undefined
                  ) {
                    return "";
                  }
                  return (params.value / 10000).toFixed(2) + "";  // 以"万"为单位显示，保留一位小数           
                },
              },
            },
            {
              name: "环比率",
              data: validHbData,
              type: "line",
              yAxisIndex: 1, // 使用第二个Y轴（环比百分比轴）
              smooth: true,
              symbol: "circle",
              symbolSize: 6,
              lineStyle: {
                width: 2,
                color: "#FAC858",
              },
              itemStyle: {
                color: function (params) {
                  return params.value >= 0 ? "#FF4500" : "#3BA272";
                },
                borderColor: "#fff",
                borderWidth: 2,
              },
              label: {
                show: false,
                position: function (params) {
                  return params.value >= 0 ? "top" : "bottom";
                },
                fontSize: 11,
                color: function (params) {
                  return params.value >= 0 ? "#FF4500" : "#FAC858";
                },
                fontWeight: "bold",
                formatter: function (params) {
                  if (params.value === null || params.value === undefined) {
                    return "";
                  }
                  if (params.value === 0) {
                    return "0%";
                  }
                  return (
                    (params.value > 0 ? "+" : "") +
                    params.value.toFixed(1) +
                    "%"
                  );
                },
              },
              markLine: {
                silent: true,
                symbol: "none",
                label: {
                  show: false,
                },
                data: [
                  {
                    yAxis: 0,
                    lineStyle: {
                      color: "rgba(51, 51, 51, 0.5)",
                      type: "solid",
                    },
                  },
                ],
              },
            },
          ],
          tooltip: {
            trigger: "axis",
            formatter: function (params) {
              let result = `${params[0].name}<br/>`;
              params.forEach(function (item) {
                if (item.seriesIndex === 0) {
                  result += `${item.marker} ${item.seriesName}: ${item.value}元<br/>`;
                } else if (item.seriesIndex === 1) {
                  if (item.value !== null && item.value !== undefined) {
                    result += `${item.marker} ${item.seriesName}: ${item.value}%`;
                  }
                }
              });
              return result;
            },
          },
        });

        setTimeout(() => {
          chart.resize();
        }, 100);
      } else {
        chart.setOption({
          title: {
            // text: "各区县总薪酬统计",
            // left: "center",
          },
          grid: {
            top: "8%",
            left: "2%",
            right: "2%",
            bottom: "0%",
            containLabel: true,
            borderWidth: 0,
            show: false,
          },
          xAxis: {
            type: "category",
            data: [
              "全市",
              "柴桑区",
              "浔阳区",
              "濂溪区",
              "共青城",
              "庐山市",
              "彭泽县",
              "德安县",
              "武宁县",
              "永修县",
              "湖口县",
              "瑞昌县",
              "都昌县",
            ],
            axisLabel: {
              rotate: 45,
              fontSize: 12,
              fontWeight: "normal",
              color: "#666666",
              fontFamily: "Arial, sans-serif",
            },
          },
          yAxis: [
            {
              type: "log",
              name: "随销收入(万元)",
              logBase: 10,
              axisLabel: {
                formatter: function (value) {
                  // if (value >= 100000000) {
                  //   return (value / 100000000).toFixed(0) + "亿";
                  // } else if (value >= 10000) {
                  //   return (value / 10000).toFixed(0) + "万";
                  // } else {
                  //   return value;
                  // }
                  if (value < 10000){
                    return (value / 10000).toFixed(1);
                  }
                  else{
                    return (value / 10000).toFixed(0);
                  }
                },
                color: "#666",
              },
              scale: true,
              splitNumber: 5,
            },
            {
              type: "value",
              name: "环比(%)",
              min: -150,
              max: 150,
              axisLabel: {
                formatter: "{value}%",
                color: "#666",
              },
            },
          ],
          series: [
            {
              name: "总收入",
              data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              type: "bar",
              itemStyle: {
                color: "#91CC75",
              },
              label: {
                show: true,
                position: "top",
                fontSize: 12,
                color: "#333",
                fontWeight: "normal",
                formatter: function (params) {
                  if (
                    params.value === 0 ||
                    params.value === null ||
                    params.value === undefined
                  ) {
                    return "";
                  }
                  return (params.value / 10000).toFixed(2) + "";  // 以"万"为单位显示，保留一位小数           
                },
              },
            },
            {
              name: "环比率",
              data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              type: "line",
              yAxisIndex: 1,
              smooth: true,
              symbol: "circle",
              symbolSize: 6,
              lineStyle: {
                width: 2,
                color: "#FAC858",
              },
              itemStyle: {
                color: "#FF4500",
                borderColor: "#fff",
                borderWidth: 2,
              },
            },
          ],
          tooltip: {
            trigger: "axis",
            formatter: function (params) {
              let result = `${params[0].name}<br/>`;
              params.forEach(function (item) {
                if (item.seriesIndex === 0) {
                  result += `${item.marker} ${item.seriesName}: ${item.value}元<br/>`;
                } else if (item.seriesIndex === 1) {
                  // 修改：不再跳过第一个数据点（全市）
                  if (item.value !== null && item.value !== undefined) {
                    result += `${item.marker} ${item.seriesName}: ${item.value}%`;
                  }
                }
              });
              return result;
            },
          },
        });

        setTimeout(() => {
          chart.resize();
        }, 100);
      }

      chartRef._echarts_instance_ = chart;
    },
  },
};
</script>

<style scoped>
.suixiao-chart {
  padding: 20px;
}
.chart-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}
/* 添加以下样式以对齐 */
.chart-description {
  font-size: 12px;
  color: #999;
}
.chart {
  height: 400px;
}
</style>
